package cn.edu.jsu.zjj.controller;

import cn.edu.jsu.zjj.annotation.AuthCheck;
import cn.edu.jsu.zjj.common.result.Result;
import cn.edu.jsu.zjj.constant.UserConstant;
import cn.edu.jsu.zjj.model.dto.UserTitle.UserTitleDeleteRequest;
import cn.edu.jsu.zjj.model.dto.UserTitle.UserTitlePageRequest;
import cn.edu.jsu.zjj.model.dto.UserTitle.UserTitleAddRequest;
import cn.edu.jsu.zjj.model.entity.UserTitle;
import cn.edu.jsu.zjj.model.utils.OtherUtils;
import cn.edu.jsu.zjj.service.UserService;
import cn.edu.jsu.zjj.service.UserTitleService;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/userTitle")
@Api(tags = "员工职称接口")
public class UserTitleController {
    @Autowired
    private UserTitleService userTitleService;
    @Autowired
    BeanSearcher beanSearcher;
    @Autowired
    private UserService userService;
    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/page")
    @ApiOperation(value = "分页查询用户工作经历", notes = "分页查询用户工作经历")
    public Result page(@RequestBody UserTitlePageRequest request){
        if(request == null || request.getUserId() == null){
            return null;
        }
        Long userId = request.getUserId();
        //页码
        Integer page = request.getPageNum();
        //每页大小
        Integer size = request.getPageSize();
        // 解析 startDateTime 和 endDateTime
        LocalDate startDateTime = OtherUtils.transformStringToLocalDate(request.getObtainDate());

        List<String> fields = Arrays.asList(request.getTitle().split(""));

        List<UserTitle> userWorks = beanSearcher.searchAll(UserTitle.class,
                MapUtils.builder()
                        .field(UserTitle::getUserId, userId)
                        .field(UserTitle::getObtainDate, startDateTime).op("gt")
                        .field(UserTitle::getTitle, fields).op("la")
                        .field(UserTitle::getIsDeleted, 0)
                        .orderBy(UserTitle::getCreateTime).desc()
                        .page(page, size)
                        .build()
        );
        Page<UserTitle> userTitlePage = new Page<>(page, size);
        userTitlePage.setRecords(userWorks);
        userTitlePage.setTotal(userWorks.size());
        return Result.success(userTitlePage);
    }

    @PostMapping("/add")
    @ApiOperation(value = "新增用户职称", notes = "新增用户职称")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.DEFAULT_ROLE})
    public Result add(@RequestBody UserTitleAddRequest request) {
        UserTitle userTitle = new UserTitle();
        BeanUtils.copyProperties(request, userTitle);
        userTitle.setCreateTime(LocalDateTime.now());
        userTitle.setUserId(request.getUserId());
        if (request.getObtainDate() == null) {
            userTitle.setObtainDate(LocalDateTime.now());
        } else {
            // 解析为 Instant 对象
            Instant instant = Instant.parse(request.getObtainDate());

            // 转换为 LocalDateTime，使用系统默认时区
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            userTitle.setObtainDate(localDateTime);
        }

        return userTitleService.save(userTitle) ? Result.success("新增成功") : Result.error("新增失败");
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除用户职称", notes = "删除用户职称")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.DEFAULT_ROLE})
    public Result delete(@RequestBody UserTitleDeleteRequest request){
        UserTitle userTitle = userTitleService.getOne(new LambdaQueryWrapper<UserTitle>().eq(UserTitle::getId,request.getId()).eq(UserTitle::getIsDeleted,0));
        if(userTitle == null){
            return Result.error("删除失败,该职称不存在或已删除");
        }
        userTitle.setIsDeleted(1);
        return userTitleService.updateById(userTitle) ? Result.success("删除成功") : Result.error("删除失败");
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "获取用户职称", notes = "获取用户职称")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.DEFAULT_ROLE})
    public Result get(@PathVariable("id") Long id){
        if(id == null){
            return Result.error("更新失败,id不能为空");
        }
        UserTitle userTitle = userTitleService.getOne(new LambdaQueryWrapper<UserTitle>().eq(UserTitle::getId,id).eq(UserTitle::getIsDeleted,0));
        if(userTitle == null){
            return Result.error("删除失败,该职称不存在或已删除");
        }
        return Result.success(userTitle);
    }

    @PutMapping("/update")
    @ApiOperation(value = "更新用户职称", notes = "更新用户职称")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.DEFAULT_ROLE})
    public Result update(@RequestBody UserTitleAddRequest request){
        if(request.getId() == null){
            return Result.error("更新失败,id不能为空");
        }
        UserTitle userTitle = userTitleService.getOne(new LambdaQueryWrapper<UserTitle>().eq(UserTitle::getId,request.getId()).eq(UserTitle::getIsDeleted,0));
        if(userTitle == null){
            return Result.error("更新失败,该职称不存在或已删除");
        }
        if(request.getObtainDate() == null){
            userTitle.setObtainDate(LocalDateTime.now());
        }else{
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            LocalDateTime localDateTime = LocalDateTime.parse(request.getObtainDate(), formatter);
            userTitle.setObtainDate(localDateTime);
        }
        BeanUtils.copyProperties(request, userTitle, "obtainDate","id");
        return userTitleService.updateById(userTitle) ? Result.success("更新成功") : Result.error("更新失败");
    }

    @PostMapping("/uploadUserTitle")
    @ApiOperation(value = "导入用户职称附件", notes = "导入用户职称")
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.DEFAULT_ROLE})
    public Result uploadUserTitle(@RequestPart("file") MultipartFile file, HttpServletRequest request,Long userId) throws Exception {
        UserTitle userTitle = userTitleService.getOne(new LambdaQueryWrapper<UserTitle>().eq(UserTitle::getUserId, userId).eq(UserTitle::getIsDeleted, 0));

        if (userTitle == null) {
            return Result.error("上传失败,该职称不存在或已删除");
        }

        // 构建请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", file.getResource());


        // 设置请求头
        String token = request.getHeader("token");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("token", token);

        // 创建 HttpEntity 对象
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送请求
        String localHostName = InetAddress.getLocalHost().getHostName();
        int localPort = request.getServerPort();
        HashMap hashMap = restTemplate.postForObject("http://" + localHostName + ":" + localPort + "/common/upload", requestEntity, HashMap.class);

        if (hashMap == null) {
            return Result.error("上传失败");
        }
        HashMap object = (HashMap) hashMap.get("data");
        String fileUrl = (String) object.get("fileUrl");
        userTitle.setFileUrl(fileUrl);
        return userTitleService.updateById(userTitle) ? Result.success("上传成功") : Result.error("上传失败");
    }
}
